<template>
  <div id="main">
    <h2>基本信息</h2>
    <div class="head">
      <el-input
        v-model="searchTableInfo"
        placeholder="请输入搜索内容"
        style="width:240px;float: right;margin-right:20px;"
      />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="studentName"
          label="姓名"
        />
        <el-table-column
          align="center"
          prop="studentAge"
          :formatter="formatAge"
          label="年龄"
        />
        <el-table-column
          align="center"
          prop="studentSex"
          :formatter="formatSex"
          label="性别"
        />
        <el-table-column
          align="center"
          prop="studentBirth"
          label="出生日期"
        />
        <el-table-column
          align="center"
          prop="studentJoinCenter"
          label="入园时间"
        />
        <el-table-column
          align="center"
          prop="studentPhone"
          label="联系电话"
        />
        <el-table-column
          align="center"
          prop="studentAccompanyTrainer"
          label="陪同训练人"
        />

        <el-table-column
          v-if="jurisdiction=='教学主管'||jurisdiction=='责任教师'||jurisdiction=='医疗主管'||jurisdiction=='教学主任'"
          align="center"
          label="操作"
        >
          <template slot-scope="Scope">
            <el-button
              v-if="jurisdiction=='教学主任'"
              type="primary"
              icon="el-icon-edit"
              @click="showDetail(Scope.row.studentId)"
            >编辑</el-button>
            <el-button
              v-else
              type="primary"
              icon="el-icon-search"
              @click="showDetail(Scope.row.studentId)"
            >查看</el-button>
          </template>
        </el-table-column>

      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- --------------------------------------------------------------------------------------------------------- -->

    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="student"
        :model="student"
        label-position="top"
        :rules="rules"
      >
        <el-form-item
          prop="studentTreatHospital"
          label="就诊医院"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatHospital"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatCurrentDiagnosis"
          label="临床判断"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatCurrentDiagnosis"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatOtherDiseases"
          label="其他疾病"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatOtherDiseases"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatTrainingAge"
          label="起训年龄"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatTrainingAge"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatPastTrainingHistoryId"
          label="既往训练记录"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatPastTrainingHistoryId"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatAttention"
          label="训练注意事项"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatAttention"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatClinicInformation "
          label="临床信息"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatClinicInformation"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatAssessmentInformation "
          label="评估信息"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatAssessmentInformation"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatDiagnosisCases "
          label="诊断病例"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatDiagnosisCases"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatTrainingPrescription "
          label="训练处方"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="student.studentTreatTrainingPrescription"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="studentTreatTime "
          label="就诊时间"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="student.studentTreatTime"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleClose"
        >取 消</el-button>
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('student')"
        >修 改</el-button>
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddUser('student')"
        >添 加</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="detailVisible"
    >
      <el-form
        ref="info"
        :model="info"
        label-position="top"
      >
        <el-form-item
          prop="studentEducationEvaluation"
          label="教育评估"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="info.studentEducationEvaluation"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 20 }"
            placeholder="请输入内容"
            :readonly="readonly"
            @input="change($event)"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >

        <el-button
          v-if="jurisdiction === '教学主任'"
          type="primary"
          @click="handleUpdateA('info')"
        >修 改</el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addChild, deleteChild, updateChild, getAllChild, getChildById, getAllParent, getAllChildA, getAllChildB, getAllChildC, getAllChildM } from '@/api/child'
import { addFather, addMother } from '@/api/parent'
import store from '@/store/index'
export default {
  data () {
    return {
      jurisdiction: '',
      BB: store.getters.userId,
      url: process.env.VUE_APP_BASE_API + 'file/',
      form: [],
      formRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[34578]\d{9}$/,
            message: '目前只支持中国大陆的手机号码'
          }
        ]
      },
      sex: [
        {
          value: 0,
          label: '女'
        },
        {
          value: 1,
          label: '男'
        }
      ],
      father: [],
      mother: [],
      String: [],
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      // list: [],
      imageUrl: '',
      tableList: [],
      searchTableInfo: '',
      train: {},
      train_id: [],
      trainingInstitutionRecordId: '',
      listLoading: false,
      dialogFormVisible: false,
      detailVisible: false,
      is_add_father: false,
      is_add_mother: false,
      is_add_train: false,
      this_stuid: '',
      readonly: false,
      editType: 1, // 1 添加 2 修改
      student: [],
      formLabelWidth: '200px',
      rules: {
        childIdcard: [
          { required: true, message: '证件号不能为空', trigger: 'blur' }
        ],
        childMedicalInfo: [
          { required: true, message: '医疗信息不能为空', trigger: 'blur' }
        ],
        childName: [
          { required: true, message: '医疗信息不能为空', trigger: 'blur' }
        ],
        childSex: [
          { required: true, message: '孩子怎么会没有性别呢', trigger: 'blur' }
        ],
        childStatus: [
          { required: true, message: '学生状态不能为空', trigger: 'blur' }
        ],
        childTeachingInfo: [
          { required: true, message: '学生教育信息不能为空', trigger: 'blur' }
        ]
      },
      info: {}
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list () {
      const searchTableInfo = this.searchTableInfo
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created () {
    this.jurisdiction = store.getters.roles[0]

    this.fetchData()
    this.getparent()
  },
  methods: {
    change (e) {
      this.$forceUpdate()
    },
    formatSex: function (row, column, cellValue) {
      if (cellValue === '1') {
        return '女'
      } else if (cellValue === '0') {
        return '男'
      }
    },
    formatAge: function (row, column, cellValue) {
      if (cellValue === -1) {
        return '未填写'
      } else {
        return cellValue
      }
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.student.studentHeadImages = this.imageUrl
    },
    beforeAvatarUpload (file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isImage && isLt2M
      // return true
    },
    getparent: function () {
      getAllParent(1).then(resp => {
        this.father = resp.data
      })
      getAllParent(0).then(r => {
        this.mother = r.data
      })
    },
    // 每页下拉显示数据
    handleSizeChange: function (size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    handleClick (row) {

    },
    fetchData () {
      this.listLoading = true
      if (this.jurisdiction === '教学主管') {
        getAllChildA(this.BB).then(data => {
          this.tableList = data.data
          this.listLoading = false
        })
      } else if (this.jurisdiction === '责任教师') {
        getAllChildB(this.BB).then(data => {
          this.tableList = data.data
          this.listLoading = false
        })
      } else if (this.jurisdiction === '医疗主管') {
        getAllChildM(this.BB).then(data => {
          this.tableList = data.data
          this.listLoading = false
        })
      } else if (this.jurisdiction === '教学主任') {
        getAllChildC(this.BB).then(data => {
          this.tableList = data.data
          this.listLoading = false
        })
      } else {
        getAllChild(this.BB).then(data => {
          this.tableList = data.data
          this.listLoading = false
        })
      }

      getAllParent(1).then(f => {
        this.father = f.data
      })
      getAllParent(0).then(m => {
        this.mother = m.data
      })
    },
    addParent (sex, childId) {
      this.is_add_father = true
    },
    addF (sex, childId) {
      this.is_add_father = true
    },
    handleOpen (title, type, id) {
      //
      this.student = []
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        this.this_stuid = id
        getChildById(id).then(resp => {
          this.student = resp.obj.student
          this.student.studentBrothers = String(this.student.studentBrothers)
          this.student.studentSex = String(this.student.studentSex)
          this.imageUrl = this.student.studentHeadImages
          this.train = resp.obj.TrainingInstitutionRecords

          for (var i = 0; i < this.train.length; i++) {
            this.form.push(this.train[i])
          }

          for (var j = 0; j < this.train.length; j++) {
            this.form[j].time = []
            this.form[j].time[0] = this.form[j].timeStart
            this.form[j].time[1] = this.form[j].timeEnd
          }
        })
      }
    },
    addM (sex, childId) {
      this.is_add_mother = true
    },
    handleDelete (id, username) {
      this.$confirm('确认删除该学生？姓名为' + username).then(() =>
        deleteChild(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil(
            (this.tableList.length - 1) / this.pagesize
          )
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },
    handleUpdate (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          updateChild(this.student).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
            this.train_id = []
            this.form = []
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleUpdateA (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          updateChild(this.info).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.detailVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAddUser (formName) {
      var allTrain = this.train_id.toString()

      this.student.studentTreatTrainingInstitutionRecords = allTrain.replace(
        /,/g,
        ';'
      )
      this.student.studentBirthtoString = this.student.studentBirth
      this.student.studentJoinCentertoString = this.student.studentJoinCenter
      this.$refs[formName].validate(valid => {
        if (valid) {
          // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa需要得到train_id列表的id（）
          addChild(this.student).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })

            this.fetchData()
            this.train_id = []
            this.form = []
          })
          this.student = []
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAddMother (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addMother(this.mother).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            getAllParent(0)
            this.fetchData()
          })
          this.mother = {}
          this.is_add_mother = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAddFather (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addFather(this.father).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })

            this.fetchData()
          })
          this.father = {}
          this.is_add_father = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleClose_f () {
      this.is_add_father = false
      this.father = {}
    },
    handleClose_m () {
      this.is_add_mother = false
      this.mother = {}
    },
    handleClose () {
      this.dialogFormVisible = false
      this.train_id = []
      this.form = []
      this.student = []
      this.imageUrl = ''
    },
    showDetail (id) {
      this.detailVisible = true
      if (this.jurisdiction === '教学主任') {
        this.readonly = false
      } else {
        this.readonly = true
      }
      for (var i = 0; i < this.tableList.length; i++) {
        if (this.tableList[i].studentId === id) {
          this.info.studentEducationEvaluation = this.tableList[i].studentEducationEvaluation
          this.info.studentId = this.tableList[i].studentId
        }
      }
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
</style>
